import {
  createRouter,
  createWebHashHistory
  // createWebHistory
  // Router
} from "vue-router";

import homeRouter from "./modules/home";

import errorRouter from "./modules/error";

import remainingRouter from "./modules/remaining"; //静态路由

import { storageLocal } from "../utils/storage";
// import { i18n } from "/@/plugins/i18n";
import { usePermissionStoreHook } from "/@/store/modules/permission";

// import { getAsyncRoutes } from "/@/api/mock";
import { getAsyncRoutes } from "/@/api/menu";
import { getProjectMenu } from "/@/api/projects";
import Layout from "/@/layout/index.vue";
// https://cn.vitejs.dev/guide/features.html#glob-import
let modulesRoutes = import.meta.glob("/src/views/*/*/*.vue");
const modulesRoutes2 = import.meta.glob("/src/views/*/*/*/*.vue");
const modulesRoutes3 = import.meta.glob("/src/views/*/*/*/*/*.vue");
modulesRoutes = Object.assign(modulesRoutes, modulesRoutes2, modulesRoutes3);
// modulesRoutes = Object.assign(modulesRoutes, modulesRoutes3);
// console.log(modulesRoutes, "modulesRoutes");

const constantRoutes: Array<any> = [homeRouter, errorRouter];

// 按照路由中meta下的rank等级升序来排序路由
export const ascending = arr => {
  // return arr.sort((a: any, b: any) => {
  //   return a?.meta?.rank - b?.meta?.rank;
  // });
  return arr;
};

// 将所有静态路由导出
export const constantRoutesArr = ascending(constantRoutes).concat(
  ...remainingRouter
);

// 过滤后端传来的动态路由重新生成规范路由
function childrenRouter(children: Array<string>) {
  if (!children || !children.length) return;
  children.forEach((k: any) => {
    k.component = modulesRoutes[`/src/views${k.path}/index.vue`];
    if (k.children?.length) {
      childrenRouter(k.children);
    }
  });
}

export const initAsyncRoutes = (children: Array<string>) => {
  if (!children || !children.length) return;
  children.forEach((k: any) => {
    k.path = k.menuPath;
    k.name = k.menuCode;
    k.meta = {
      icon: k.icon,
      title: k.menuName,
      showLink: k.isDisplay === "Y" ? true : false,
      // showLink: true,
      rank: k.menuOrder,
      savedPosition: false
    };
    if (k.children && k.children?.length) {
      const filterMenu = k.children.filter(item => {
        return item.isDisplay === "Y";
      });
      if (filterMenu?.length) {
        k.redirect = filterMenu[0].menuPath;
      }
    }
    if (k.children && k.children?.length) {
      initAsyncRoutes(k.children);
    }
  });
  return children;
};

export const addAsyncRoutes = (arrRoutes: Array<string>) => {
  if (!arrRoutes || !arrRoutes.length) return;
  arrRoutes.forEach((v: any) => {
    // if (v.redirect) {
    v.component = Layout;
    // } else {
    //   v.component = modulesRoutes[`/src/views${v.path}/index.vue`];
    // }
    if (v.children?.length) {
      childrenRouter(v.children);
    }
  });
  return arrRoutes;
};

const router = createRouter({
  // history: createWebHashHistory(),
  // history: createWebHistory(import.meta.env.VITE_PUBLIC_PATH),
  history: createWebHashHistory(import.meta.env.VITE_BASE as any),
  routes: ascending(constantRoutes).concat(...remainingRouter),
  scrollBehavior(to, from, savedPosition) {
    return new Promise(resolve => {
      if (savedPosition) {
        return savedPosition;
      } else {
        if (from.meta.saveSrollTop) {
          const top: number =
            document.documentElement.scrollTop || document.body.scrollTop;
          resolve({ left: 0, top });
        }
      }
    });
  }
});

const treeToArr = data => {
  const result = [];
  data.forEach(item => {
    const loop = data => {
      result.push({
        id: data.id,
        name: data.name,
        parentId: data.parentId,
        menuName: data.menuName,
        menuCode: data.menuCode,
        menuPath: data.menuPath,
        path: data.path
      });
      const child = data.children;
      if (child) {
        for (let i = 0; i < child.length; i++) {
          loop(child[i]);
        }
      }
    };
    loop(item);
  });
  return result;
};

/**
 * 从后台请求路由信息。并动态加入路由实例中
 * */
export const initRouter = (name, next?, to?) => {
  return new Promise(resolve => {
    if (
      to &&
      (to.fullPath.indexOf("projectsB") > -1 ||
        to.fullPath.indexOf("projectsA") > -1 ||
        to.fullPath.indexOf("projectsS") > -1)
    ) {
      let sectionId = "";
      if (to.fullPath.indexOf("projectsB") > -1) {
        sectionId = "B";
      } else if (to.fullPath.indexOf("projectsA") > -1) {
        sectionId = "A";
      } else if (to.fullPath.indexOf("projectsS") > -1) {
        sectionId = storageLocal.getItem("sectionInfo")?.id + "";
      }
      const params = {
        projectManageId: storageLocal.getItem("projectInfo")?.id,
        sectionId: sectionId
      };
      getProjectMenu(params)
        .then(res => {
          if (res.code === 200) {
            const info = res?.data ?? [];
            if (info?.length) {
              const nextRoute = info[0]?.children;
              const arrayRoute = treeToArr(nextRoute);
              if (
                arrayRoute.findIndex(value => value.menuPath === to.path) !== -1
              ) {
                //页面权限中由当前页面的url,当前访问页面url可能带有参数
                handleMenu(to, next, info);
                resolve(router);
              } else {
                router.push("/error/404");
              }
            } else {
              router.push("/error/404");
            }
          }
        })
        .catch(error => {
          const code = error?.response?.status;
          if ([401, 403].includes(code)) {
            storageLocal.removeItem("info");
            router.push("/login");
          }
        });
    } else {
      getAsyncRoutes({})
        .then(res => {
          if (res.code === 200) {
            const info = res?.data ?? [];
            console.log(810, info, router.getRoutes());
            handleMenu(to, next, info);
          }
          resolve(router);
        })
        .catch(error => {
          console.log(error, "init_error");
          const code = error?.response?.status;
          if ([401, 403].includes(code)) {
            storageLocal.removeItem("info");
            router.push("/login");
          }
        });
    }
  });
};

const handleMenu = (to, next, info) => {
  // 过滤出与当前路径相应的路由
  if (to && to.fullPath) {
    const routeKeyword = to.fullPath.split("/")[1];
    const filterRouter = info.filter(item => {
      return item.menuPath.split("/")[1] === routeKeyword;
    });
    // info = filterRouter
    info =
      (filterRouter[0] &&
        filterRouter[0].children.length &&
        filterRouter[0].children) ||
      {};
  }
  console.log(info, "infoinfoinfo");
  // 过滤出头部一级路由
  if (info.length) {
    info = initAsyncRoutes(info);
  }
  if (info && info.length === 0) {
    usePermissionStoreHook().changeSetting(info);
  } else {
    console.log(123, info);
    addAsyncRoutes(info).map((v: any) => {
      // 防止重复添加路由
      if (router.getRoutes().findIndex(value => value.path === v.path) !== -1) {
        usePermissionStoreHook().clearRoute(info);
        return;
      } else {
        // 切记将路由push到routes后还需要使用addRoute，这样路由才能正常跳转
        if (v?.path) {
          router.options.routes.forEach(item => {
            if (item.path === v.path) {
              router.options.routes.push(v);
            }
          });
        }
        // 最终路由进行升序
        ascending(router.options.routes);
        router.addRoute(v.name, v);

        if (next && to) next({ ...to, replace: true });
        usePermissionStoreHook().changeSetting(info);
      }
    });
  }
  // 最后加入404 防止刷新时直接进入404页面
  // if (router.getRoutes()
  //     .findIndex(value => value.path === "/:pathMatch(.*)") === -1
  // ) {
  //   router.addRoute({
  //     path: "/:pathMatch(.*)",
  //     redirect: "/error/404"
  //   });
  // }
};

// reset router
const whiteList = [
  "/login",
  "/logout",
  "/login",
  "/register",
  "/",
  "/welcome",
  "/home",
  "/:pathMatch(.*)",
  "/error/401",
  "/error/404",
  "/error",
  "/redirect",
  "/profile",
  "/redirect/:path(.*)",
  "/analysis",
  "/systems",
  "/preview",
  "/preview3D"
];

export function resetRouter() {
  router.getRoutes().forEach(route => {
    const { name } = route;
    if (name && !whiteList.includes(route.path)) {
      router.hasRoute(name) && router.removeRoute(name);
    }
  });
}

import NProgress from "../utils/progress";

router.beforeEach(async (to, _from, next) => {
  // console.log(to, _from);
  NProgress.start();
  // const { t } = i18n.global;
  // @ts-ignore
  // to.meta.title ? (document.title = t(to.meta.title)) : ""; // 动态title
  // const externalLink = to?.redirectedFrom?.fullPath;
  // @ts-ignore
  // if (!externalLink) to.meta.title ? (document.title = t(to.meta.title)) : "";
  // if (externalLink && externalLink.includes("http")) {
  //   // @ts-ignore
  //   openLink(`http${split(externalLink, "http")[1]}`);
  //   NProgress.done();
  // } else {
  //   next();
  // }
  // next();

  // 路由变化前, 获取下一个页面的权限
  if (!["/login", "/logout"].includes(to.path)) {
    const res = await usePermissionStoreHook().getBtnAuth(
      to.path as string,
      to.query as any
    );
    next();

    const name = storageLocal.getItem("info")?.name ?? "";
    console.log("name:", name, "res:", res, "init menu");

    if (name) {
      const router: any = await initRouter(name, next, to);
      // 将query参数携带
      router.push({ path: to.path, query: to.query });
      next();
    }
    // await initRouter(name, next, to).then((router: Router) => {
    //   // 将query参数携带
    //   router.push({ path: to.path, query: to.query });
    //   next();
    // });
  } else {
    next();
    usePermissionStoreHook().resetSetting();
    resetRouter();
  }

  // }
  // next();

  // } else {
  //   if (to.path !== "/login") {
  //     if (to.path === "/register") {
  //       next();
  //     } else {
  //       next({ path: "/login" });
  //     }
  //   } else {
  //     next();
  //   }

  //   usePermissionStoreHook().resetSetting();
  //   resetRouter();
  // }
});

router.afterEach(() => {
  NProgress.done();
  // setTimeout(() => {
  //   ElNotification.closeAll();
  // }, 1000);
});

export default router;
